#include "widget.h"
#include "ui_widget.h"
#include<QByteArray>
#include <QDebug>
#include <QHostAddress>
#include<QBuffer>
#include <QFile>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    v4l2 = NULL;
    //实例化一个定时器类的对象
    m_timer = new QTimer;
    connect(m_timer,&QTimer::timeout,this,&Widget::onUpdateCameraUi);
    //启动摄像头
    if(v4l2 == NULL)
    {
        v4l2 = new V4l2Api("/dev/video7");

        v4l2->start();//必须要等摄像头开启之后
        m_timer->start(50); //才能启动定时器，让定时器 每隔50ms采集一次数据并且显示出来
    }

    //1、实例化服务器类的对象
    m_tcpServer = new QTcpServer;

    QString iP = QString("127.0.0.1");
    short port = 1234;
    // 2、绑定和监听
     m_tcpServer->listen(QHostAddress(iP),port);

    //3、当有新的客户端连接上来，会自动发射信号newConnect信号
    connect(m_tcpServer,&QTcpServer::newConnection,this,&Widget::onNewClientConnect);

}

Widget::~Widget()
{
    delete ui;
}
void  Widget::onNewClientConnect()
{
    qDebug()<<"connect succes";
    //在槽函数中获取新客户端的连接
    tcpClient = m_tcpServer->nextPendingConnection();
    //当有客户端发送数据的时候，tcpClient会触发readyRead信号，关联槽函数，接收数据
    connect(tcpClient,&QTcpSocket::readyRead,this,&Widget::onRecvDataSlot);

}

void Widget:: onRecvDataSlot()
{
   saveImg.save("2.bmp");
   //加载图图片
    QImage image("2.bmp");
   //将图片转换成字节数组
    QByteArray imgeData;
    QBuffer buffer(&imgeData);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer,"BMP");
    //发送
    int ret =  tcpClient->write(imgeData);
    qDebug()<<ret;



//   saveImg.save("1.bmp");
//   system("scp 1.bmp gec@192.168.6.45:/mnt/hgfs/GZFX2302/11QT/build-car3-Desktop_Qt_5_14_2_MinGW_64_bit-Debug");
}

void Widget::onUpdateCameraUi()
{
    char buffer[640*480*3] = {0};
    char rgbdata[640*480*3] = {0};
    int size;
    //采集数据
    v4l2->get_frame(buffer,&size);

    //yuyv格式 转换成  rgb格式
    v4l2->yuv422torgb24((unsigned char*)buffer,(unsigned char*)rgbdata,640,480);

    //显示 ---rgbdata
    QImage img((unsigned char*)rgbdata,640,480,QImage::Format_RGB888);
    saveImg = img;
    QPixmap pic = QPixmap::fromImage(img);
    pic = pic.scaled(ui->label->size());
    ui->label->setPixmap(pic);





}


